package com.tgy.JUC.producerConsumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/***
 * @ClassName: PCJUC
 * @Description: JUC 版本的生产者消费者
 * @Auther: 送你一块二向箔
 * @Date: 9:59 2022/3/11
 * @version : V1.0
 */
public class PCJUC {
    public static void main(String[] args) {
        Data2 data = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) data.increment();
        }, "A").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) data.decrement();
        }, "B").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) data.increment();
        }, "C").start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) data.decrement();
        }, "D").start();
    }

}

// 判断等待，业务，通知  共用一个锁 生产者消费者的关键
class Data2 {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    private int i = 0;

    // +1
    public void increment() {
        lock.lock();
        try {
            while (i != 0) {
                condition.await();
            }
            i++;
            System.out.println(Thread.currentThread().getName() + "=>" + i);
            // 通知其他线程我+1完成
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    // -1
    public void decrement() {
        lock.lock();
        try {
            //业务代码
            while (i == 0) {
                condition.await();
            }
            i--;
            System.out.println(Thread.currentThread().getName() + "=>" + i);
            // 通知其他线程，我-1完毕
            condition.signalAll();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}


